<?php

namespace App\Controller;

use App\Model\Table\UserTable;
use App\Model\User\UserRecord;
use App\Model\User\UserRow;
use App\Service\UserService;
use App\UnifiedResponse;
use Atlas\Orm\Atlas;
use Cake\ORM\Locator\TableLocator;
use Doctrine\ORM\EntityManager;
use Faker\Factory;
use Symfony\Component\Yaml\Dumper;
use Wonfu\Core\Annotations\RequestTag;
use Wonfu\Core\Annotations\Valid;
use Wonfu\Core\Annotations\RequestMapping;
use App\Entity\User;
use DI\Annotation\Inject;
use Symfony\Component\Validator\Validation;
use Wonfu\Core\AppController;
use Wonfu\Core\Database\BaseAtlas;
use Wonfu\Core\Utils;
use Wonfu\Http\ServerRequest;
use Twig\Environment;
use Wonfu\Http\ServerResponse;
use Monolog\Logger;


/**
 * Description of UserCtrller
 *
 * @author vison.cao <visonforcoding@gmail.com>
 * @RequestTag(name="用户",description="用户模块包括登录、注册")
 */
class UserCtrller extends AppController
{

    /**
     * @Inject
     * @var UserService
     */
    private $userService;



    /**
     * @Valid(validParamsIn="requestBody",contentType="application/json",paramKey="user")
     * @RequestMapping(name="添加用户",path="/user",method="POST")
     * @param User $user
     */
    public function add(User $user)
    {
        $faker = Factory::create('zh_CN');
        $name = $faker->name;
        $user->setName($name);
        $this->atlas->insert($user);
        return new UnifiedResponse(0, '插入成功', $user);
    }

    /**
     * @RequestMapping(name="用户详情",path="/user/{id:\d+}",method="GET")
     */
    public function detail(int $id): UnifiedResponse
    {
        $user = $this->userService->gainDetail($id);
        return new UnifiedResponse(0, '获取成功', $user);
    }

    /**
     * @RequestMapping(name="用户列表",path="/users",method="GET")
     */
    public function users(): UnifiedResponse
    {
        /** @var UserRecord $users */
        $users = $this->atlas->select(\App\Model\User\User::class)->with(['addresses'])->where('id > ', 0)
            ->andWhere('age > ', 1)->fetchRecordSet();
//        dump($users->getArrayCopy());
        /** @var User $user */
        $user = Utils::ObjectMapper(json_encode($users->getArrayCopy()), User::class . "[]");
        return new UnifiedResponse(0, '获取成功', $user);
    }

    /**
     * @RequestMapping(name="用户列表forcake",path="/user/list",method="GET")
     */
    public function userList(): UnifiedResponse
    {

        $userTable = new UserTable();
        $user = $userTable->getQueryBuilder()->contain(['address'])->firstPoPoObject();

        return new UnifiedResponse(0,'',$user);

    }


    /**
     * @RequestMapping(name="用户登录",path="/user/login",method="GET")
     * @return UnifiedResponse
     */
    public function login(): UnifiedResponse
    {
        if ($this->userService->login() == 'login') {
            return new UnifiedResponse(0, '登录成功');
        }
        return new UnifiedResponse(1, '登录失败');
    }



}
